﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Business;
using System.Collections.ObjectModel;
using System.Collections;
using BitPortal.Models;
using BitPortal.Utils;


namespace BitPortal.Admin.Services.Error
{
	public partial class Default : Controls.BaseAdminPage
	{
		protected override void OnInit(EventArgs e)
		{
			PermissionBLL.CheckRoleThrowException(role: "ErrorView", useExceptionHandler: true);
			base.OnInit(e);
            (this.errorAdd1 as Controls.BaseAdminControl).ReloadControls.Add(this.GridPanel1);
            
		}

		protected void Page_Load(object sender, EventArgs e)
		{

		}
		public void LoadGridData()
		{
			(this.Master as AdminFunction).MasterResourceManager.AddScript("Ext.getCmp('" + GridPanel1.ClientID + "').getStore().reload();");
			(this.GridPanel1.SelectionModel.Primary as RowSelectionModel).ClearSelections();
		}

        /// <summary>
        /// Create new work
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
		protected void btnAdd_Click(object sender, DirectEventArgs e)
		{
            try
            {
                PermissionBLL.CheckRoleThrowException("WorkInsert", useExceptionHandler: true);
	            RowSelectionModel rm= this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
	            if (rm.SelectedRows.Count>0)
	            {
	                long errorId=Convert.ToInt64(rm.SelectedRows[0].RecordID);
	                workAddEdit1.BindDataFromError(errorId);
                    
	            }

                LoadGridData();
                
            }
            catch (System.Exception ex)
            {
                ShowNotification(ex.Message, "Thông báo", Icon.Error);
            }
            //(new Models.ErrorReport()).ProductCustomer.Customer.ContactName
            
		}

        /// <summary>
        /// Edit this error
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
		protected void btnEdit_Click(object sender, DirectEventArgs e)
		{
            try
            {
                PermissionBLL.CheckRoleThrowException("ErrorEdit", useExceptionHandler: true);
                RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                if (sm.SelectedRows.Count > 0)
                {
                    long id = Convert.ToInt64(sm.SelectedRows[0].RecordID);
                    errorAdd1.BindData(id);
                }
                LoadGridData();
            }


            catch (SystemException ex)
            {
                ShowNotification(ex.Message, "Thông báo", Icon.Error);
            }
           
		}

        /// <summary>
        /// Bind data to grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
		protected void Store1_RefreshData(object sender, StoreRefreshDataEventArgs e)
		{
			List<Models.ErrorReport> data;
            if (Session["ErrorGridFlag"] != null && Session["ErrorGridFlag"].Equals(false))
            {
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                data = bitEnt.ErrorReports.Where(ent => ent.IsDeleted == true).ToList();
            }
            else
            {
                long id=GeneralUtils.ToInt64TryParse(Request.QueryString["ProductCustomerId"]);
                
                if ( id != 0)
                {
                    data = ErrorReportBLL.GetByProductCustomer(id).ToList();
                }
                else
				    data = ErrorReportBLL.GetAll().ToList();
			}
			FilterConditions fc = null;
			string s = e.Parameters[this.GridFilters1.ParamPrefix];
			if (!string.IsNullOrEmpty(s))
			{
				fc = new FilterConditions(s);
			}
			this.Store1.DataSource = ExtNet.GirdData.Filter<Models.ErrorReport>(data, fc, e);
		}

		protected void btnDelete_Click(object sender,EventArgs e)
		{
            try
            {
                PermissionBLL.CheckRoleThrowException("ErrorDelete",useExceptionHandler:true);
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    long ID = Convert.ToInt64(row.RecordID);
                    BitPortal.Models.ErrorReport error = bitEnt.ErrorReports.SingleOrDefault(ent => ent.ErrorID == ID);
                    if (error != null)
                    {
                        error.IsDeleted = true;
                    }
                    
                }
               
                int record = bitEnt.SaveChanges();
                Notification.Show(new NotificationConfig
                {
                    Title = "Thông báo",
                    Icon = Icon.Information,
					Html = "Xóa " + record + " lỗi thành công!"
                });
                sm.ClearSelections();
                LoadGridData();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
		}

		protected void btnTrashEmpty_Click(object sender, EventArgs e)
		{
			try
			{
				PermissionBLL.CheckRoleThrowException("ErrorDelete",useExceptionHandler:true);

				int record = 0;
				ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
				foreach (BitPortal.Models.ErrorReport a in bitEnt.ErrorReports.Where(ent => ent.IsDeleted ==true).ToList())
				{
					if (ErrorReportBLL.DeletePermanently(a.ErrorID) > 0)
					{
						record++;
					}
				}
				Notification.Show(new NotificationConfig
				{
					Title = "Thông báo",
					Icon = Icon.Information,
					Html = "Xóa " + record + " lỗi trong thùng rác thành công!"
				});
				LoadGridData();
			}
			catch (Exception ex)
			{
				ShowMessage(ex.Message);
			}
		}

		protected void btnTrashDelete_Click(object sender, EventArgs e)
		{
			try
			{
				PermissionBLL.CheckRoleThrowException("ErrorDelete",useExceptionHandler:true);

				int record = 0;
				RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
				foreach (SelectedRow row in sm.SelectedRows)
				{
					if (ErrorReportBLL.DeletePermanently(Convert.ToInt64(row.RecordID)) > 0)
					{
						record++;
					}
				}
				Notification.Show(new NotificationConfig
				{
					Title = "Thông báo",
					Icon = Icon.Information,
					Html = "Xóa " + record + " lỗi trong thùng rác thành công!"
				});
				sm.ClearSelections();
				LoadGridData();
			}
			catch (Exception ex)
			{
				ShowMessage(ex.Message);
			}
		}

        protected void btnUnDelete_Click(object sender, EventArgs e)
		{
			try
			{
				PermissionBLL.CheckRoleThrowException("ErrorEdit",useExceptionHandler:true);
				ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
				RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
				foreach (SelectedRow row in sm.SelectedRows)
				{
					long ID = Convert.ToInt64(row.RecordID);
					BitPortal.Models.ErrorReport error = bitEnt.ErrorReports.SingleOrDefault(ent => ent.ErrorID == ID);
                    if (error != null)
                    {
                        error.IsDeleted = false;
                        error.StateError = (int)StateError.Chuaduyet;
                    }
				}
				int record = bitEnt.SaveChanges();
				Notification.Show(new NotificationConfig
				{
					Title = "Thông báo",
					Icon = Icon.Information,
					Html = "Khôi phục  " + record + " lỗi thành công!"
				});
				LoadGridData();
			}
			catch (Exception ex)
			{
				ShowMessage(ex.Message);
			}

		}

		protected void btnTrash_Click(object sender, DirectEventArgs e)
		{
			if (Session["ErrorGridFlag"] != null && Session["ErrorGridFlag"].Equals(false))
			{
				Session["ErrorGridFlag"] = true;
			}
			else
			{
				Session["ErrorGridFlag"] = false;
			}
			LoadGridData();
		}



        protected void btnSetState_Click(object sender, DirectEventArgs e)
        {
            try
            {
               
                PermissionBLL.CheckRoleThrowException("ErrorEdit",useExceptionHandler:true);
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    long ID = Convert.ToInt64(row.RecordID);
                    BitPortal.Models.ErrorReport error = bitEnt.ErrorReports.SingleOrDefault(ent => ent.ErrorID == ID);
                    if (error != null)
                        error.StateError=Convert.ToInt32(cbxState.SelectedItem.Value);
                }
                int record = bitEnt.SaveChanges();
                if (record > 0)
                {
                    ShowNotification("Cập nhật " + record + " lỗi thành công!");
                    LoadGridData();
                }
                Window3.Hide();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

       
        
        [DirectMethod]
        public void LoadErrors(string errorID)
        {
            this.wProductDetail.AutoLoad.Url = "/Admin/Service/ProductCustomer/?ErrorID=" + errorID;
            this.wProductDetail.LoadContent();
            this.wProductDetail.Show();
        }

        
        //protected void Store2_RefreshData(object sender, StoreRefreshDataEventArgs e)
        //{
        //    List<Models.ErrorReport> data = null;
        //    if (Session["ErrorGridFlag"] != null && Session["ErrorGridFlag"].Equals(false))
        //    {
        //        ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
        //        data = bitEnt.ErrorReports.Where(ent => ent.IsDeleted == true).ToList();
        //    }
        //    else
        //    {
        //        RowSelectionModel rm=this.GridPanel1.SelectionModel.Primary as RowSelectionModel;

        //        if (rm.SelectedRows.Count>0)
        //        {

        //            long id = GeneralUtils.ToInt64TryParse(rm.SelectedRows[0].RecordID);

        //            if (id != 0)
        //            {
        //                data = ErrorReportBLL.GetAllErrors(id).ToList();
                       
        //            }
        //        }
                

        //    }
        //    FilterConditions fc = null;
        //    string s = e.Parameters[this.GridFilters1.ParamPrefix];
        //    if (!string.IsNullOrEmpty(s))
        //    {
        //        fc = new FilterConditions(s);
        //    }
        //    this.Store2.DataSource = ExtNet.GirdData.Filter<Models.ErrorReport>(data, fc, e);
            
        //    //GridPanel2.Reload();
        //}
       
    }
}